package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xuecheng.base.exception.CommonError;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.content.mapper.TeachplanMapper;
import com.xuecheng.content.mapper.TeachplanMediaMapper;
import com.xuecheng.content.model.dto.SaveTeachplanDto;
import com.xuecheng.content.model.dto.TeachplanDto;
import com.xuecheng.content.model.po.Teachplan;
import com.xuecheng.content.model.po.TeachplanMedia;
import com.xuecheng.content.service.TeachplanService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class TeacherplanServiceImpl implements TeachplanService {
    @Autowired
    private TeachplanMapper teachplanMapper;
    @Autowired
    private TeachplanMediaMapper teachplanMediaMapper;

    @Override
    public List<TeachplanDto> findTeachplanTree(Long courseId) {
        return teachplanMapper.selectTreeNodes(courseId);
    }

    /**
     * 新增或修改课程计划
     *
     * @param saveTeachplanDto
     */
    @Override
    public void saveTeachplan(SaveTeachplanDto saveTeachplanDto) {
        //通过课程计划id判断是新增还是修改
        Long teachplanId = saveTeachplanDto.getId();
        if (teachplanId == null) {
            //新增
            Teachplan teachplan = new Teachplan();
            BeanUtils.copyProperties(saveTeachplanDto, teachplan);
            //确定排序字段，找到他的同级节点个数，排序字段就是个数加1
            Long parentid = saveTeachplanDto.getParentid();
            Long courseId = saveTeachplanDto.getCourseId();
            int teachplanCount = getTeachplanCount(parentid, courseId);
            teachplan.setOrderby(teachplanCount);
            teachplanMapper.insert(teachplan);
        } else {
            //修改
            Teachplan teachplan = teachplanMapper.selectById(teachplanId);
            BeanUtils.copyProperties(saveTeachplanDto, teachplan);
            teachplanMapper.updateById(teachplan);
        }

    }

    /**
     * 找到同级节点个数，个数+1
     *
     * @param parentid
     * @param courseId
     * @return
     */
    private int getTeachplanCount(Long parentid, Long courseId) {
        LambdaQueryWrapper<Teachplan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Teachplan::getCourseId, courseId).eq(Teachplan::getParentid, parentid);
        Integer count = teachplanMapper.selectCount(queryWrapper);
        return count + 1;

    }

    /**
     * 删除课程计划
     *
     * @param id
     */
    @Override
    @Transactional
    public void deleteTeachplan(Long id) {
        //1.判断是第几级别
        Teachplan teachplan = teachplanMapper.selectById(id);
        if (teachplan == null) {
            throw new XueChengPlusException(CommonError.OBJECT_NULL.getErrMessage());
        }
        Long courseId = teachplan.getCourseId();
        int orderCount = 1;
        //查询子节点
        List<Teachplan> teachplanChilds = teachplanMapper.selectList(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getParentid, id));
        //查询同级别节点
        List<Teachplan> teachplans = teachplanMapper.selectList(new LambdaQueryWrapper<Teachplan>().eq(Teachplan::getCourseId, courseId).eq(Teachplan::getGrade, 1));
        if (teachplan.getGrade() == 1) {
            if (teachplanChilds.size() > 0) {
                throw new XueChengPlusException("该课程计划下有子节点，不能删除");
            }
//            for (int i = 1; i <=teachplans.size(); i++) {
//                if (teachplans.get(i).getId().equals(id)) {
//                    teachplanMapper.deleteById(id);
//                }else {
//                    teachplans.get(i).setOrderby(orderCount);
//                    orderCount++;
//                    teachplanMapper.updateById(teachplans.get(i));
//                }
//            }
            for (Teachplan t : teachplans) {
                if (t.getId().equals(id)) {
                    teachplanMapper.deleteById(id);
                } else {
                    t.setOrderby(orderCount);
                    orderCount++;
                    teachplanMapper.updateById(t);
                }
            }

        }//TODO 看不到子节点喵
        else if (teachplan.getGrade() == 2) {
            LambdaQueryWrapper<TeachplanMedia> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TeachplanMedia::getTeachplanId, id);
            Integer mediaCount = teachplanMediaMapper.selectCount(wrapper);
            for (int i = 1; i <= teachplanChilds.size(); i++) {
                if (teachplan.getId().equals(id)) {
                    if (mediaCount > 0) {
                        teachplanMediaMapper.delete(wrapper);
                    }
                    teachplanMapper.deleteById(id);
                } else {
                    teachplans.get(i).setOrderby(orderCount);
                    orderCount++;
                    teachplanMapper.updateById(teachplans.get(i));
                }
            }

        }
    }

    /**
     * 课程计划上移下移
     *
     * @param moveType
     * @param id
     */
    @Override
    @Transactional
    public void moveTeachplan(String moveType, Long id) {
        //1.判断是第几级别
        Teachplan teachplan = teachplanMapper.selectById(id);
        Integer orderby = teachplan.getOrderby();
        Long courseId = teachplan.getCourseId();

        if (teachplan == null) {
            throw new XueChengPlusException(CommonError.OBJECT_NULL.getErrMessage());
        }
        Integer grade = teachplan.getGrade();
        LambdaQueryWrapper<Teachplan> wrapper = new LambdaQueryWrapper<>();
        if (grade == 1) {
            wrapper.eq(Teachplan::getGrade, grade).eq(Teachplan::getCourseId, courseId);
        }
        if (grade == 2) {
            wrapper.eq(Teachplan::getParentid, teachplan.getParentid()).eq(Teachplan::getGrade, grade);
        }
        List<Teachplan> teachplans = teachplanMapper.selectList(wrapper);
        int i = 0;
        if (teachplans.size() > 1) {
            if (StringUtils.equals(moveType, "moveup")) {
                for (Teachplan t : teachplans) {
                    //找到当前章节的排序字段减一,以此获得上一个章节
                    if (t.getOrderby() == (orderby - 1) && (orderby - 1) != 0) {
                        i++;
                    }
                    if (i == 1) {
                        //进行交换
                        teachplan.setOrderby(t.getOrderby());
                        t.setOrderby(orderby);
                        teachplanMapper.updateById(t);
                        teachplanMapper.updateById(teachplan);
                        break;
                    }
                }
                if (i == 0) {
                    XueChengPlusException.cast("当前计划已经在顶部，无法交换");
                }
            } else {
                for (Teachplan t : teachplans) {
                    //找到当前章节的排序字段加一,以此获得下一个章节
                    if (t.getOrderby() == (orderby + 1) && (orderby + 1) != teachplans.size()) {
                        i++;
                    }
                    if (i == 1) {
                        //进行交换
                        teachplan.setOrderby(t.getOrderby());
                        t.setOrderby(orderby);
                        teachplanMapper.updateById(t);
                        teachplanMapper.updateById(teachplan);
                        break;
                    }

                }
                if (i == 0) {
                    XueChengPlusException.cast("当前计划已经在底部，无法交换");
                }
            }
        }

    }

}